//
//  NDWebViewModel.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/11/1.
//

import SwiftUI
import WebKit
import StoreKit

class NDWebViewModel: ObservableObject {
    @Published var progress: Double = 0.0
    @Published var showProgress: Bool = false
    @Published var canGoBack: Bool = false
    @Published var shouldClose: Bool = false
    @Published var shouldGoHome: Bool = false
    @Published var title: String = ""
    
    private var webView: WKWebView?
    
    var startTime: Int = 0
    
    func loadWebContent(urlString: String?) {
        guard let urlString = urlString,
              let url = URL.buildURL(with: urlString) else { return }
        
        let request = URLRequest(url: url)
        webView?.load(request)
        startTime = Int(Date().timeIntervalSince1970)
    }
    
    func goBack() {
        webView?.goBack()
    }
    
//    private func buildURL(with urlString: String) -> URL? {
//        guard var urlComponents = URLComponents(string: urlString) else {
//            return nil
//        }
//        
//        let commonParams = NDNetworkService.shared.requestBuilder.commonParameters
//        let commonQueryString = commonParams.urlQueryString
//        
//        guard !commonQueryString.isEmpty else {
//            return urlComponents.url
//        }
//        
//        // 解析公共参数字符串为 URLQueryItem 数组
//        let commonQueryItems = commonQueryString.components(separatedBy: "&").compactMap { pair -> URLQueryItem? in
//            let components = pair.components(separatedBy: "=")
//            guard components.count == 2 else { return nil }
//            return URLQueryItem(name: components[0], value: components[1])
//        }
//        
//        // 合并查询参数
//        var existingQueryItems = urlComponents.queryItems ?? []
//        existingQueryItems.append(contentsOf: commonQueryItems)
//        urlComponents.queryItems = existingQueryItems
//        
//        return urlComponents.url
//    }
    
    // JavaScript 消息处理
    func handleJavaScriptMessage(_ message: WKScriptMessage, navManager: NavigationViewManager) {
        switch message.name {
        case "pirevidenceacious": // 风控埋点
            handleTheTracking(message: message)
        case "charge": // 跳转原生或者H5
            handleNavigation(message: message, navManager: navManager)
        case "trud": // 关闭当前 H5
            shouldClose = true
        case "phenoality": // 回到 App 首页
            shouldGoHome = true
        case "frugcy": // 打开系统邮箱
            openEmail(message: message)
        case "productionence": // 应用评分
            requestReview()
        default:
            break
        }
    }
    
    private func handleTheTracking(message: WKScriptMessage) {
        guard let body = message.body as? [Any],
              body.count >= 2 else { return }
        
        let productId: Int?
        if let number = body[0] as? Int {
            productId = number
        } else if let string = body[0] as? String {
            productId = Int(string)
        } else {
            productId = nil
        }
        
        guard let orderNum = body[1] as? String,
              let productId = productId else { return }
        
        NDEventAnallyticsTool.uploadMaiDianEvent(maiDianType: .endLoan,
                                                 productId: productId,
                                                 orderNum: orderNum,
                                                 startTimeStamp: startTime,
                                                 endTimeStamp: Int(Date().timeIntervalSince1970))
    }
    
    private func handleNavigation(message: WKScriptMessage, navManager: NavigationViewManager) {
        guard let url = message.body as? String else { return }
        
        if url.hasPrefix("http") || url.hasPrefix("https") {
            // 打开新的 WebView
            navManager.pushView(tag: mainNav) {
                NDWebView(urlString: url,
                          isFollowOrder: false,
                          isPresent: false)
            }
        } else {
            // 处理原生跳转
            NDSchemeManager.shared.handleURL(url)
        }
    }
    
    private func openEmail(message: WKScriptMessage) {
        guard let email = message.body as? String else { return }
        
        let phone = NDUserDefaults.shared.retrieveText(for: NDPhoneNumberKey)
        let urlString = "mailto:\(email)?body=NyamanDana,\(phone ?? ""):"
        
        if let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
           let url = URL(string: encodedURLString),
           UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
    
    func requestReview() {
        if #available(iOS 14.0, *) {
            if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
                SKStoreReviewController.requestReview(in: windowScene)
            }
        } else {
            SKStoreReviewController.requestReview()
        }
    }
    
    func updateProgress(_ progress: Double) {
        self.progress = progress
        self.showProgress = progress < 1.0
    }
    
    func updateNavigationState(canGoBack: Bool) {
        self.canGoBack = canGoBack
    }
    
    func updateNavigationTitle(_ title: String) {
        self.title = title
    }
    
    func setWebView(_ webView: WKWebView) {
        self.webView = webView
    }
}

